'use strict'
const Controller = require('../base.js')
const qiniu = require('qiniu')
const uuid = require('uuid/v1')

const AK = 'TH1Kl1BwLXdERTMyr6wddEWv7BIdFnWv8jeQGcaH'
const SK = 'zYI8Uw_QvLjbKUDvhFNb0cAECLbsvXJdqCSUmKAb'

const mac = new qiniu.auth.digest.Mac(AK, SK)

const putPolicy = new qiniu.rs.PutPolicy({
    scope: 'eggcms',
    expires: 100
})


let config = new qiniu.conf.Config()
config.zone = qiniu.zone.Zone_z0
config.useCdnDomain = true
const formUploader = new qiniu.form_up.FormUploader(config)
const putExtra = new qiniu.form_up.PutExtra()

const fileUpLoad = (key, stream, putExtra) => {
    let uploadToken = putPolicy.uploadToken(mac)
    return new Promise((reslove, reject) => {
        formUploader.putStream(uploadToken, key, stream, putExtra, (respErr, respBody, respInfo) => {
            if (respErr) {
                reject(respErr)
            } else {
                if (respInfo.statusCode == 200) {
                    reslove(respBody)
                } else {
                    reject({respBody, respInfo})
                }
            }
        })
    })
}

class FileQiniuController extends Controller {
    // 上传文件
    async index() {
        const {ctx, app} = this
        const stream = await ctx.getFileStream()
        // 截取文件类型
        let filename = stream.filename
        let t = filename.split('.')
        let len = t.length
        let filetypeName = '.' + t[len - 1]
        let key = uuid() + filetypeName

        try {
            const res = await fileUpLoad(key, stream, putExtra)
            ctx.success({
                url: res.key,
                hash: res.hash,
                origin: 'qiniu'
            })
        } catch (e) {
            console.log('上传七牛出错', e)
            ctx.throw(500, '上传七牛出错', {
                code: 'qiniu_error',
                errors: e
            })
        }
    }
}

module.exports = FileQiniuController
